package ce.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bat.db.BaseDAOImpl;
import net.bat.util.Cfg;
import net.cs.um.UMService;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;


import org.hibernate.SQLQuery;
import org.hibernate.Session;


//import avens.util.SessionUtil;
import ce.service.AuthServiceImpl;
import ce.service.AvensHlp;
//import dao.hb.AvensResource;
import dao.hb.NBase;
import dao.hb.PinFunmapping;
import dao.hb.PinObjmapping;
import dao.hb.UGrant;
import dao.hb.UGroup;

public class Authenticate extends HttpServlet {
	public static final String SE_USERNAME = "SE_USERNAME";
	public static final String COOKIE_OBJ = "COOKIE_OBJ";
	public static final String COOKIE_FUNC = "COOKIE_FUNC";
	public static final String COOKIE_USER = "COOKIE_USER";
	public static final String COOKIE_UN = "COOKIE_UN";
	public static final String COOKIE_ROLE = "COOKIE_ROLE";
	public static final String TICKET_NAME = "CAS_TICKET";
	public static final String COOKIE_ORGID = "COOKIE_ORGID";
	public static String URL_CASHOME = null;
	public static String URL_CASHOME_LOCAL = null;
	public static String loginURL;
	public static String logoutURL;
	public static String valicationURL;
	public static String recallURL;
	public static String redirectionURL;
	private BaseDAOImpl dao = null;
	
	
	public BaseDAOImpl getDao() {
		if (dao == null)
			dao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
		return dao;
	}

	public void setDao(BaseDAOImpl dao) {
		this.dao = dao;
	}

	public void init(ServletConfig config) throws ServletException {
		if (URL_CASHOME != null)
			return;
		super.init(config);
		//URL_CASHOME = AvensConstants.CasHome; //wjh  
		URL_CASHOME = Cfg.getInitParameter("avens.CasHome"); //wjh  
		//URL_CASHOME_LOCAL = AvensConstants.LocalHome;
		URL_CASHOME_LOCAL = Cfg.getInitParameter("avens.LocalHome"); //wjh
		loginURL = URL_CASHOME + "login";
		logoutURL = URL_CASHOME + "logout";
		valicationURL = URL_CASHOME + "serviceValidate";
		recallURL = URL_CASHOME_LOCAL + "servlet/authenticate";
		redirectionURL = loginURL + "?service=" + recallURL;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
    /*
	public void testAddUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String cas = (String) request.getParameter("cas");//cas=createpersion
		if (cas==null || (!cas.equals("createpersion"))) {
			return;
		}
		
		//增加用户
		AuthServiceImpl authServiceImpl = (AuthServiceImpl) Cfg.getBean("AuthServiceImpl");
		try {
			authServiceImpl.testCreate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		String cmd = (String) request.getParameter("cmd");
		
		boolean devAdduser = false;//wjh 测试增加用户
		
		if (devAdduser){   //测试增加用户
			//testAddUser(request,response);			
			return;
		}
		
//		if (devAdduser && (1==0)){	
//			// 登录系统   http://127.0.0.1:8080/ipcm/servlet/authenticate?ticket=aaaa
//			String user="cn=110108198103096884"; 
//			try {
//				String roles = AvensHlp.login(user, null, null, request);  //roles "dpm_ce;;dpm_ce_djr";
//System.out.println("*********roles="+roles); //*roles=dpm_ce;;dpm_ce_bjr,dpm_ce;;dpm_ce_shr,dpm_ce;;dpm_ce_fyr,dpm_ce;;dpm_ce_djr,dpm_ce;;dpm_ce_xdr
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
//			return;
//		}
		
		if (cmd != null && cmd.equals("logout")) {
			response.sendRedirect(logoutURL);
			return;
		}
		String ticket = (String) request.getParameter("ticket");  //ST-24-mQ0s1iNItbuxlLcXcUgUtI3m1uMmxYWJEhjP0FHwfTfkLKf1Dw
		if (ticket == null) {
			ticket = (String) request.getSession().getAttribute(TICKET_NAME);
		}
		String default_cmd = (String) request.getParameter("default_cmd");
		if (default_cmd == null)
			default_cmd = "";
		if (ticket == null) {
			response.sendRedirect(loginURL + "?service=" + recallURL);  //loginURL : login , recallURL:  servlet/authenticate ->http://127.0.0.1:8080/ipcm/servlet/login?service=servlet/authenticate
			return;
		}
		String reqURL = valicationURL + "?service=" + recallURL + "&ticket="
				+ ticket + "&default_cmd=" + default_cmd;//http://192.168.1.45:8088/cas/serviceValidate?service=http://127.0.0.1:8080/ipcm/servlet/authenticate&ticket=ST-24-mQ0s1iNItbuxlLcXcUgUtI3m1uMmxYWJEhjP0FHwfTfkLKf1Dw&default_cmd=
		request.getSession().setAttribute(TICKET_NAME, ticket);

		try {
			doResponse(getResponse(reqURL, "GBK"), request, response);  //最后 : http://127.0.0.1:8080/ipcm/ipc/main.html?cas=true
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	
	private String getResponse(String reqURL, String cset)
			throws HttpException, IOException {
		HttpClientParams params = new HttpClientParams();
		params.setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(0, true));
		HttpClient httpclient = new HttpClient(
				new MultiThreadedHttpConnectionManager());
		httpclient.setParams(params);
		System.out.println("******************reqURL="+reqURL);
		System.out.println("******************cset="+cset);
		GetMethod getMethod = new GetMethod(reqURL);
		int statusCode = httpclient.executeMethod(getMethod);
		byte[] rb = getMethod.getResponseBody();
		String rstr = new String(rb, cset);
		// String rstr=getMethod.getResponseBodyAsString();
		getMethod.releaseConnection();
		return rstr;//<cas_serviceResponse>\r\n  <cas_authenticationSuccess>\r\n    <cas_user>cn=110108198103096884,ou=zhanshijishuke,ou=ziliaoxinxizhongxin,dc=gugong</cas_user>\r\n         <cas_userdesc>郭?</cas_userdesc>\r\n    <cas_loginMode>password</cas_loginMode>\r\n  </cas_authenticationSuccess>\r\n</cas_serviceResponse>\r\n
	}
	
	
//s:<cas_serviceResponse>\r\n  <cas_authenticationSuccess>\r\n    <cas_user>cn=110108198103096884,ou=zhanshijishuke,ou=ziliaoxinxizhongxin,dc=gugong</cas_user>\r\n         <cas_userdesc>郭?</cas_userdesc>\r\n    <cas_loginMode>password</cas_loginMode>\r\n  </cas_authenticationSuccess>\r\n</cas_serviceResponse>\r\n
	private void doResponse(String s, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int i, i1, i2, i3, i4;
		i = s.indexOf("<cas_authenticationSuccess>");
		i1 = s.indexOf("<cas_user>");
		i2 = s.indexOf("</cas_user>");
		i3 = s.indexOf("<cas_userdesc>");
		i4 = s.indexOf("</cas_userdesc>");

		String userdn = "", user = "", loginmode = "", orgid = "", userdesc = "", orgname = "", orgdn = "";
		if ((i >= 0) && (i1 >= 0) && (i2 >= 0)) {
			userdn = s.substring(i1 + 10, i2);
			i1 = s.indexOf("<cas_loginMode>");
			i2 = s.indexOf("</cas_loginMode>");
			if ((i1 >= 0) && (i2 >= 0))
				loginmode = s.substring(i1 + 15, i2);
			i1 = userdn.indexOf(",");
			if (i1 > 0) {
				orgdn = userdn.substring(i1 + 1);
				user = userdn.substring(0, i1);
				String[] orglist = orgdn.split(",");
				if (orglist.length > 1) {
					orgid = orglist[orglist.length - 2].replaceAll("ou=", "");
					orgdn = orglist[orglist.length - 2] + ","
							+ orglist[orglist.length - 1];
				}
			}
		}

		// 更新用户信息
//System.out.println("1111*********orgid=" + "ou%3D" + orgid);  // ou%3Dziliaoxinxizhongxin		
		orgname = getpropertyfromURL("ou%3D" + orgid);	   //orgid : ziliaoxinxizhongxin//orgname=资料信息中心
//System.out.println("orgname="+orgname);                     

		String un = getpropertyfromURL("cn%3D" + user.substring(3)); //cn%3D  user : "cn=110108198103096884"//un=郭珽
		
		 
//System.out.println("222*********user.substring= " + "cn%3D" + user.substring(3));	
//System.out.println("un="+un);   

		// 登录系统 , 返回用户组                                        //user : cn=110108198103096884
		String roles = AvensHlp.login(user, null, null, request); // return:DEV  //:"dpm_ce;;dpm_ce_djr";//user "cn=110108198103096884"
		
		
		
//System.out.println("***************roles="+roles);   //un=郭珽
		// 设置cookie引导进入ccp
		//c4w 2.25 去掉角色限制,允许登入
		//if (!roles.equals("")) {
			StringBuffer sbuf = new StringBuffer();
			StringBuffer sbuf2 = new StringBuffer();
			String hql = "from PinObjmapping where username=?";
		
			//取数据集权限 
			List ls = getDao().find(hql, new Object[] { user });  //user : cn=110108198103096884
			if (ls != null && ls.size() > 0) {
				for (int k = 0; k < ls.size(); k++) {
					//PinObjmapping om = (AvensObjmapping) ls.get(k);
					PinObjmapping om = (PinObjmapping) ls.get(k); //wjh
					if (k == 0)
						//sbuf.append(om.getObjName());
					    sbuf.append(om.getDatasetId());  //wjh
					else
						//sbuf.append(";" + om.getObjName());
					    sbuf.append(";" + om.getDatasetId()); //wjh
				}
			}
			
			//取功能权限
			//String hql2 = "from AvensFunmapping where username=?";
			/*
			String hql2 = "from UGroup A, UGrant B where A.id=B.gid and A.name=?";
			List ls2 = getDao().find(hql2, new Object[] { roles });
			if (ls2 != null && ls2.size() > 0) {
				int len = ls2.size();
				for(int k=0; k<len; k++){
					Object[] os = (Object[])ls2.get(k);
					UGrant ugrant = (UGrant)os[1];
					if (k == 0)
						sbuf2.append(ugrant.getPmMenu());
					else
						sbuf2.append(";" + ugrant.getPmMenu());  //8;9
				}
			}*/
			String sql="select * from u_group  a,u_user  b where a.id=b.gid and b.user_id='"+user+"'";
			BaseDAOImpl baseDao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
			Session session = baseDao.getSessionFactory().getCurrentSession();	
			SQLQuery query =session.createSQLQuery(sql).addEntity(UGroup.class);
			List<UGroup> ls_group=(List<UGroup>)query.list();
			int len = ls_group.size();
			String pm_menu="";
			for(int j=0; j<len; j++){
				UGroup cur = ls_group.get(j);
				if(j==0)
					pm_menu+=cur.getGrantMenu();
				else
					pm_menu+=";"+cur.getGrantMenu();
			}
				
//			if (ls2 != null && ls2.size() > 0) {
//				for (int k = 0; k < ls2.size(); k++) {
//					//AvensFunmapping om = (AvensFunmapping) ls2.get(k);
//					PinFunmapping om = (PinFunmapping) ls2.get(k);
//					if (k == 0)
//						sbuf2.append(om.getFunName());
//					else
//						sbuf2.append(";" + om.getFunName());
//				}
//			}
			//c4w 3.29
			request.getSession().setAttribute(SE_USERNAME, un.trim());
			request.getSession().setAttribute("userId", user);
			
			response.addCookie(getCookie(COOKIE_USER, user));         //user "cn=110108198103096884"
			response.addCookie(getCookie(COOKIE_UN, un));           //郭珽
			response.addCookie(getCookie(COOKIE_ROLE, roles));      //DEV
			response.addCookie(getCookie(COOKIE_ORGID, orgid));       // ziliaoxinxizhongxin
			response.addCookie(getCookie(COOKIE_OBJ, sbuf.toString()));  //pindatasetpersion
			response.addCookie(getCookie(COOKIE_FUNC, pm_menu));  //8   功能权限
			//response.sendRedirect("../bat/cc/cc.html?cas=true"); // 通过统一身份验证登录系统
			response.sendRedirect("../cm/main.html?cas=true"); //http://127.0.0.1:8080/ipcm/ipc/main.html?cas=true
			//http://localhost:8080/ipcm/ipc/main.html
		//}//c4w 2.25
	}

	private Cookie getCookie(String cn, String cv) {
		Cookie ck = null;
		try {
			ck = new Cookie(cn, URLEncoder.encode(cv.trim(), "UTF-8"));
			ck.setMaxAge(-1);
			ck.setPath("/");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ck;
	}

	private void setCookies(HttpServletResponse response, String user,
			String un, String roles) {
		response.addCookie(getCookie(COOKIE_USER, user));
		response.addCookie(getCookie(COOKIE_UN, un));
		response.addCookie(getCookie(COOKIE_ROLE, roles));
	}

	//example : pn : 110108198103096884
	public String getpropertyfromURL(String pn) throws HttpException,
			IOException {
		String url = Cfg.getInitParameter("avens.UmHome") +  Cfg.getInitParameter("avens.URLgetproperty") + "?dn=" + pn
				+ "&attrlist=description&receivemode=1";  // Cfg.getpropertyURL:queryinfo
		return getResponse(url, "utf-8");//url:http://192.168.1.45:8088/um/queryinfo?dn=ou%3Dziliaoxinxizhongxin&attrlist=description&receivemode=1
	}
}
